import fetch from "node-fetch";
import crypto from "crypto";
import common from "../../lib/common/common.js";

const keywords = {
  'yue': ['粤语', '粤'],
  'kor': ['韩语', '韩文', '韩'],
  'th': ['泰语', '泰'],
  'pt': ['葡萄牙语', '葡萄牙', '葡萄', '葡'],
  'el': ['希腊语', '希腊', '希'],
  'bul': ['保加利亚语', '保加利亚', '保'],
  'fin': ['芬兰语', '芬兰', '芬'],
  'slo': ['斯洛文尼亚语', '斯洛文尼亚', '斯'],
  'cht': ['繁体中文', '繁体', '繁中', '繁文', '繁'],
  'zh': ['中文', '中'],
  'wyw': ['文言文', '文言'],
  'fra': ['法语', '法'],
  'ara': ['阿拉伯语', '阿拉伯', '阿'],
  'de': ['德语', '德'],
  'nl': ['荷兰语', '荷兰', '荷'],
  'est': ['爱沙尼亚语', '爱沙尼亚', '爱沙', '爱'],
  'cs': ['捷克语', '捷克', '捷'],
  'swe': ['瑞典语', '瑞典', '瑞'],
  'vie': ['越南语', '越南', '越'],
  'en': ['英语', '英文', '英'],
  'jp': ['日语', '日文', '日'],
  'spa': ['西班牙语', '西班牙', '西'],
  'ru': ['俄语', '俄文', '俄'],
  'it': ['意大利语', '意大利', '意'],
  'pl': ['波兰语', '波兰', '波'],
  'dan': ['丹麦语', '丹麦', '丹'],
  'rom': ['罗马尼亚语', '罗马尼亚', '罗'],
  'hu': ['匈牙利语', '匈牙利', '匈']
};

//前往https://api.fanyi.baidu.com/注册获取APP ID和密钥
let aid = ''  
let mid = ''

let word = 'zh'  //默认翻译的语言
export class baidufanyi extends plugin {
    constructor() {
        super({
            /** 功能名称 */
            name: '百度翻译',
            /** https://oicqjs.github.io/oicq/#events */
            event: 'message',
            /** 优先级，数字越小等级越高 */
            priority: 99,
            rule: [
                {
                    reg: '^#(.*)翻(译)?(.*)$',
                    fnc: 'fanyi'
                },
				{
                    reg: '^#?语(言|种)列表$',
                    fnc: 'yuyan'
                }
            ]
        })
    }
  
  
  async yuyan(e) {
	let msgs = [`指令格式：#翻译/xx  #翻译日语/xx  #中翻日/xx\n使用 “#翻译/xx” 默认翻译成${keywords[word][0]}`]
	let msg = ''
    for (let code in keywords) {
        let key = keywords[code].join('，')
		msg += `${code}：${key}\n`
    }
	msgs.push(msg)
	await e.reply(await common.makeForwardMsg(e, msgs));
	return true
  }
  
  async fanyi(e) {
	if (!aid || !mid) {
		logger.info(`未配置相关参数`)
		return false
	}
	let msg = e.msg
	let stringlist = msg.split('/');
    let tag = stringlist[0]
    let key = stringlist[1]

	let beforeTranslate, afterTranslate
	let regex = /(.*?)翻(译)?(.*)/
    let match = tag.match(regex)
    if (match) {
        let a = match[1].trim()
        let b = match[3].trim()
		beforeTranslate = matchLanguageCode(a)
        afterTranslate = matchLanguageCode(b)
    } 
	
	if (!beforeTranslate) beforeTranslate = 'auto'
	if (!key) {
		key = tag.replace(/#|翻(译)?/g, '').trim();
	}
	if (!afterTranslate) {
		if (isChinese(key)) {
            afterTranslate = 'en'; 
        } else {
            afterTranslate = 'zh'; 
        }
	}
	
	logger.info(`${beforeTranslate}→${afterTranslate}：${key}`)
	
	let randomNumber = Math.floor(Math.random() * 100000000)
	let salt = String(randomNumber).padStart(8, '0')
	let md5Hash = crypto.createHash('md5').update(`${aid}${key}${salt}${mid}`).digest('hex')
	
	let api = `http://api.fanyi.baidu.com/api/trans/vip/translate?q=${key}&from=${beforeTranslate}&to=${afterTranslate}&appid=${aid}&salt=${salt}&sign=${md5Hash}`
	try {
	    let response = await fetch(api);
        let res = await response.json();
	
	    e.reply(res.trans_result[0].dst, true)
	} catch(error) {
		e.reply(`请求失败`, true)
	}
	return true
  }
  	
}

function matchLanguageCode(input) {
        for (let code in keywords) {
            if (keywords[code].includes(input)) {
                return code;
            }
        }
        return '';
    }

function isChinese(text) {
    const chineseRegex = /[\u4e00-\u9fff]|[\u3400-\u4dbf]|[\u{20000}-\u{2a6df}]|[\u{2a700}-\u{2b73f}]|[\u{2b740}-\u{2b81f}]|[\u{2b820}-\u{2ceaf}]|[\uf900-\ufaff]|[\u3300-\u33ff]|[\ufe30-\ufe4f]|[\uf900-\ufaff]|[\u{2f800}-\u{2fa1f}]/u;
    return chineseRegex.test(text);
}
	
	